<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="托盘码" prop="tray_id">
        <el-input v-model="queryParams.tray_id" placeholder="请输入托盘码" clearable size="small" />
      </el-form-item>
      <el-form-item label="业务单号" prop="customer_business_number">
        <el-input v-model="queryParams.customer_business_number" placeholder="业务单号" clearable size="small" />
      </el-form-item>
      <el-form-item label="数量">
        <el-input v-model="queryParams.number" placeholder="数量" clearable size="small" />
      </el-form-item>
      <el-form-item label="批次号">
        <el-input v-model="queryParams.batch_number" placeholder="批次号" clearable size="small" />
      </el-form-item>
      <el-form-item label="入库日期" prop="created_at">
        <el-date-picker
          v-model="queryParams.created_at"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <!--      <el-form-item label="入库时间" prop="created_at">-->
      <!--        <el-input v-model="queryParams.tray_id" placeholder="请输入托盘码" clearable size="small" />-->
      <!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="zdfp">自动分配</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-tag type="success" size="medium">要求出库数量:{{ number }}</el-tag>
      </el-col>
      <el-col :span="1.5">
        <el-tag type="success" size="medium">已出库数量:{{ pick_out_num }}</el-tag>
      </el-col>
      <el-col :span="1.5">
        <el-tag type="warning" size="medium">选中数量:{{ seleNum }}</el-tag>
      </el-col>
      <el-col :span="1.5">
        <el-tag type="warning" size="medium">已锁定数量:{{ self_all_counts }}</el-tag>
      </el-col>
      <el-col :span="1.5">
        <el-tag type="warning" size="medium">系统预分配数量:{{ generate_all_counts }}</el-tag>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleAdd"
        >锁定</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          v-if="(Number(this.number) - Number(this.pick_out_num)) !== Number(this.seleNum)"-->
      <!--          type="info"-->
      <!--          plain-->
      <!--          icon="el-icon-check"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--        >锁定</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="multiple"
          @click="handleDel"
        >删除锁定</el-button>
      </el-col>
    </el-row>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      @select="onSelect"
    >
      <el-table-column type="selection" align="center" width="50" :selectable="selectable" />
      <el-table-column prop="goods_name" label="商品名称" align="center" width="90" :show-overflow-tooltip="true" />
      <el-table-column prop="goods_name" label="包装(数量/单位)" align="center" width="120">
        <template v-slot="scope">
          {{ scope.row.packing_num + '/' + scope.row.unit_name }}
        </template>
      </el-table-column>

      <el-table-column prop="finNum" label="仓库数量" align="center" sortable />
      <el-table-column prop="_locking_num" label="拣货锁定数量" align="center" sortable />
      <el-table-column label="拣货数量" align="center">
        <template v-slot="scope">
          <!-- @keyup.native="pickNumber(scope.row)" -->
          <!-- oninput="value=this.value.replace(/\D+/g,'');if(value.length>11)value=value.slice(0,11)" -->
          <el-tooltip
            v-if="scope.row.disabled === 'disabled'"
            class="item"
            effect="light"
            content="正在移库中，不可编辑"
            placement="top"
          >
            <el-input
              v-model="scope.row.number"
              :disabled="scope.row.disabled"
              @input="con($event, scope.row.stock_pid)"
              @click.native="pickin(scope.row)"
            />
          </el-tooltip>
          <el-input
            v-else
            v-model="scope.row.number"
            :disabled="scope.row.disabled"
            @input="con($event, scope.row.stock_pid)"
            @click.native="pickin(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="config_name" label="库位" align="center" />
      <el-table-column prop="tray_id" label="托盘码" align="center" sortable />
      <el-table-column prop="batch_number" label="批次号" align="center" />
<!--      <el-table-column prop="customer_business_number" label="客户业务单号" align="center" />-->
       <el-table-column prop="sn" label="SN码(多个用逗号分开，如：SN001,SN002)" align="center" >
      <template v-slot="scope">
        <el-input
          type="textarea"
          v-model="scope.row.sn"
        />
      </template>
       </el-table-column>
<!--      <el-table-column prop="box_id" label="箱号" align="center" />-->
<!--      <el-table-column prop="slice_id" label="片号" align="center" />-->
<!--      <el-table-column prop="LOT1" label="LOT1" align="center">-->
<!--        <template v-slot="scope">-->
<!--          <el-input-->
<!--            v-model="scope.row.LOT1"-->
<!--            size="mini"-->
<!--          />-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column prop="LOT2" label="LOT2" align="center">-->
<!--        <template v-slot="scope">-->
<!--          <el-input-->
<!--            v-model="scope.row.LOT2"-->
<!--            size="mini"-->
<!--          />-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column prop="LOT3" label="LOT3" align="center">-->
<!--        <template v-slot="scope">-->
<!--          <el-input-->
<!--            v-model="scope.row.LOT3"-->
<!--            size="mini"-->
<!--          />-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="created_at" label="入库时间" align="center" :show-overflow-tooltip="true" sortable />
    </el-table>
  </div>
</template>

<style scoped>

</style>

<script>
import { pickList, pickAdd, pickDel } from '@/api/stock'
export default {
  name: 'StockPick',
  data() {
    return {
      // 遮罩层
      loading: true,
      open: false,
      title: '',
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      form: {},
      selectData: [],
      // 查询参数
      queryParams: {
        tray_id: undefined,
        type: 1
      },
      info: [],
      ids: [],
      pick_number: 0,
      pick_number1: 0,
      number: 0,
      warehouse_out_id: '',
      warehouse_out_son_id: '',
      xtFpNum: 0,
      self_all_counts: 0,
      generate_all_counts: 0,
      seleNum: 0,
      pick_out_num: 0
    }
  },
  computed: {
    surplus() {
      let num = 0
      this.list.forEach((item) => {
        if (item.number) {
          num += Number(item.number)
        }
      })
      // this.number = this.$route.query.number
      // console.log('number', this.number)
      // console.log('num', num)
      return this.number - num
    }
    // seleNum() {
    //   let num = 0
    //   this.list.forEach((item) => {
    //     if (item.number) {
    //       num += Number(item.number)
    //     }
    //   })
    //   return num
    // }
  },
  watch: {
    list(val) {
      this.$nextTick(() => {
        this.list.forEach((item, index, arr) => {
          this.list[index].if_selection = true
          if (item._self_pick_num || item._generate_pick_num) {
            this.$refs.multipleTable.toggleRowSelection(item, true)

          }
        })
        this.seleNumFun()
      })
    }
  },
  activated() {
    this.getList()
  },
  created() {
    this.getList()
  },
  methods: {
    // selectPick() {
    //   this.pick_number = 0
    //   for (let i = 0; i < this.list.length; i++) {
    //     if (this.list[i].if_selection) {
    //       this.pick_number += Number(this.list[i].number)
    //     }
    //   }
    // },
    zdfp() {
      this.queryParams['type'] = 0
      this.getList()
    },
    selectable(row, rowIndex) {
      // 索引是从0开始，条件1是指只有第2行数据不被禁用
      if (row.disabled === 'disabled') {
        return false // 禁用
      } else {
        return true // 不禁用
      }
    },
    con(event, pid) {
      var that = this
      // console.log(event)
      this.list.forEach((item) => {
        if (item.stock_pid === pid) {
          item.number = event.replace(/\D+/g, '')
        }
        if (String(item.number).length > 11) {
          item.number = item.number.slice(0, 11)
        }
        if (Number(item.Hold_Qty) > 0 || Number(item.NG_Qty) > 0) {
          if (item.stock_pid === pid) {
            if (item.firstInput) {
              this.$confirm('货物状态为HOLD/NG, 请确认是否分配该货物?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                item.firstInput = false
                console.log('item.firstInput', item.firstInput)
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消操作'
                })
                item.number = ''
              })
            }
          }
        }
        if (Number(item.number) > Number(this.number)) {
          item.number = this.number
        }
        if (Number(item.Good_Qty) > 0) {
          if (Number(item.number) > Number(item.Good_Qty - item._locking_num)) {
            item.number = Number(item.Good_Qty - item._locking_num)
            this.$message.error('拣货数量不能大于库存数量')
          }
        } else if (Number(item.Hold_Qty) > 0) {
          if (Number(item.number) > Number(item.Hold_Qty - item._locking_num)) {
            item.number = Number(item.Hold_Qty - item._locking_num)
            this.$message.error('拣货数量不能大于库存数量')
          }
        } else if (Number(item.NG_Qty) > 0) {
          if (Number(item.number) > Number(item.NG_Qty - item._locking_num)) {
            item.number = Number(item.NG_Qty - item._locking_num)
            this.$message.error('拣货数量不能大于库存数量')
          }
        }
        if (item.number) {
          this.$refs.multipleTable.toggleRowSelection(item, true)
          item.if_selection = true
        } else {
          this.$refs.multipleTable.toggleRowSelection(item, false)
          item.if_selection = false
        }
        if (item.number == 0) {
          this.$refs.multipleTable.toggleRowSelection(item, false)
          item.if_selection = false
          item.number = null
        }
      })
      let z_num = 0
      this.list.forEach(item => {
        if (item.if_selection && item.stock_pid !== pid) {
          z_num += Number(item.number)
        }
      })
      this.list.forEach((item) => {
        if (item.stock_pid === pid) {
          if (Number(item.number) > Number(this.number - z_num)) {
            item.number = this.number - z_num
            this.$message.error('选中数量不能大于出库数量')
          }
        }
      })
      this.seleNumFun()
    },
    seleNumFun() {
      this.seleNum = 0
      this.list.forEach((item) => {
        if (item.if_selection) {
          this.seleNum += Number(item.number)
        }
      })
    },
    onSelect(selection, row) {
      this.list.forEach((item) => {
        item.if_selection = false
      })
      selection.forEach((item) => {
        this.list.forEach((item1) => {
          if (item.stock_pid === item1.stock_pid) {
            item1.if_selection = true
          }
        })
      })
      this.seleNumFun()
      // console.log('this.list', this.list)
      // this.selectPick()

    // this.pick_number = 0
    // for (let i = 0; i < selection.length; i++) {
    //   if (selection[i].number) {
    //     this.pick_number += Number(selection[i].number)
    //   }
    // }
    // console.log('pick_number', this.pick_number)
    },
    fpNumber() {
      let a_num = this.number
      let sd_num = 0
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].number) {
          sd_num += Number(this.list[i].number)
        }
      }
      if (sd_num == this.number) {
        return
      }
      if (sd_num < this.number) {
        a_num = this.number - sd_num
      }
      this.list.forEach((item) => {
        if (!item.number && a_num > 0 && Number(item.locking) < Number(item.Good_Qty)) {
          if (a_num > item.Good_Qty && Number(item.locking)) {
            item.number = Number(item.Good_Qty) - Number(item.locking)
            a_num -= item.number
          } else if (a_num > item.Good_Qty) {
            item.number = item.Good_Qty
            a_num -= item.Good_Qty
          } else {
            item.number = a_num
            a_num = 0
          }
        }
      })
    // this.pick_number = this.number
    },
    /** 查询列表 */
    getList() {
      const that = this
      this.loading = true
      this.queryParams['warehouse_out_son_id'] = this.$route.query.warehouse_out_son_id
      this.queryParams['warehouse_out_id'] = this.$route.query.warehouse_out_id
      this.warehouse_out_id = this.$route.query.warehouse_out_id
      this.warehouse_out_son_id = this.$route.query.warehouse_out_son_id
      // this.number = this.$route.query.number
      pickList(this.queryParams).then(response => {
        if (response.code === 10000) {
          that.list = response.data.stock
          // this.pickNumber('', 2)
          that.number = response.data.out_son.number
          that.self_all_counts = response.data.out_son._self_all_counts
          that.generate_all_counts = response.data.out_son._generate_all_counts
          that.pick_out_num = response.data.out_son._pick_out_num
          that.fpNumber()
          that.list.forEach((item) => {
            item.number = null
            if (item._self_pick_num == 0) {
              item._self_pick_num = null
            }
            if (item._generate_pick_num == 0) {
              item._generate_pick_num = null
            }
            if (item._self_pick_num) {
              item.number = item._self_pick_num
            }
            if (item._generate_pick_num) {
              item.number = item._generate_pick_num
            }
            item.firstInput = true
          })
          that.list.forEach(item => {
            if (item.Good_Qty > 0) {
              item.finNum = item.Good_Qty + '(Good)'
            } else if (item.Hold_Qty > 0) {
              item.finNum = item.Hold_Qty + '(Hold)'
            } else if (item.NG_Qty > 0) {
              item.finNum = item.NG_Qty + '(NG)'
            }
          })
          console.log('that.list', that.list)
          that.loading = false
        }
      })
    },
    /** 锁定 */
    handleAdd() {
      this.$confirm('捡货锁定，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            // instance.confirmButtonLoading = true
            // instance.confirmButtonText = '锁定中...'

            this.info = []
            this.list.map(item => {
              if (item.if_selection) {
                const info = {
                  number: item.number,
                  tray_id: item.tray_id,
                  box_id: item.box_id,
                  slice_id: item.slice_id,
                  stock_id: item.stock_stock_id,
                  LOT1: item.LOT1,
                  LOT2: item.LOT2,
                  LOT3: item.LOT3,
                  sn: item.sn,
                }
                this.info.push(info)
                this.ids.push(item.id)
              }
            })
            const data = {
              info: this.info,
              warehouse_out_id: this.warehouse_out_id,
              warehouse_out_son_id: this.warehouse_out_son_id
            }
            // console.log('info', this.info)
            // return
            pickAdd(data).then(response => {
              if (response.code === 10000) {
                // this.$message.success(response.message)
                this.$notify({
                  title: '成功',
                  message: response.message,
                  type: 'success'
                })
                this.getList()
              }
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        }
      }).then(() => {

      })
    },
    pickin(row) {
      // return
      if (!row.number && row.Good_Qty !== row.locking) {
        this.list.forEach((item, index) => {
          if (item.stock_pid === row.stock_pid) {
            this.list[index].number = this.surplus > parseInt(row.Good_Qty) ? row.Good_Qty - row.locking : this.surplus
          }
        })
      }
      // this.selectPick()
      this.info.forEach((item) => {
        if (item.stock_pid === row.stock_pid) {
          item.number = row.number
        }
      })
    },
    /** 编辑按钮操作 */
    handleEdit(row) {

    },
    /** 删除锁定 */
    handleDel() {
      const that = this
      that.ids = []
      that.list.forEach((item) => {
        if (item.if_selection) {
          that.ids.push(item.stock_stock_id)
        }
      })
      that.$confirm('是否删除锁定数据？？？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
      // console.log('that.ids', that.ids);
      // return
        that.loading = true
        pickDel({ ids: that.ids, warehouse_out_son_id: that.warehouse_out_son_id }).then(response => {
          that.loading = false
          if (response.code === 10000) {
            that.getList()
            that.$notify({
              title: '成功',
              message: response.message,
              type: 'success'
            })
            // that.$message.success(response.message)
          } else {
            that.$notify({
              title: '失败',
              message: response.message,
              type: 'error'
            })
            // that.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        tray_id: undefined,
        type: 1
      }
      this.handleQuery()
    },
    /** 选中的项 */
    handleSelectionChange(selection) {
      this.info = []
      selection.map(item => {
        if (item.if_selection) {
        // if (item.number && item.number > 0) {
          const info = {
            number: item.number,
            tray_id: item.tray_id,
            box_id: item.box_id,
            slice_id: item.slice_id
          }
          this.info.push(info)
          this.ids.push(item.id)
        }
      })
      this.multiple = !selection.length
    // console.log('info', this.info)
    },
    pickNumber(row = null, type) {
      if (row.number == undefined) return
      if (isNaN(row.number)) {
        row.number = 0
      }
      if (type === 2) {
        let sum = 0
        this.list.forEach((item) => {
          if (item.number) {
            sum += parseInt(item.number)
          }
        })
        this.pick_number = sum
      } else {
        const Good_Qty = row.Good_Qty
        const locking = row.locking
        const number2 = (Good_Qty - locking)
        // console.log('surplus', this.surplus)
        if (this.surplus < 0) {
          row.number = parseInt(row.number) + this.surplus
        }
        if (row.number > number2) {
          row.number = number2
          this.$message.warning('拣货数量不可大于仓库数量')
        }
        let sum = 0
        this.list.forEach((item) => {
          if (item.number) {
            sum += parseInt(item.number)
          }
        })
        this.pick_number = sum
      }
      // console.log(this.list)
      this.selectPick()
      this.info.forEach((item) => {
        if (item.tray_id === row.tray_id) {
          item.number = row.number
        }
      })
    }

  }
}
</script>

